
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  ProductInStockGetProductCategoriesName,
  GetProductInStockCategoryNums,
  ProductInStockCreate
} from "@/api/stu/SupplyChainFinance"
import * as echarts from 'echarts';
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
export function useSupplierWarehouse() {
  const route = useRoute();
  const dataList = ref<any>([]);
  const loading = ref<boolean>(true);
  const dataList2 = ref<any>([]);
  const loading2 = ref<boolean>(true);
  const DialogVisible = ref<boolean>(false);
  const AddVisible = ref<boolean>(false);
  const RefStubimAddFrom = ref();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 50
    }, {
      label: "产品名称",
      prop: "supplyName",
    }, {
      label: "型号",
      prop: "supplyName",
    }, {
      label: "动库类型（出库）",
      prop: "supplyName",
    }, {
      label: "数量",
      prop: "supplyName",
    }, {
      label: "金额",
      prop: "supplyName",
    }, {
      label: "日期",
      prop: "supplyName",
    }
  ]
  const columns2: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 50
    }, {
      label: "电商企业",
      prop: "supplyName",
    }, {
      label: "商品信息",
      prop: "supplyName",
    }, {
      label: "状态",
      prop: "supplyName",
    }, {
      label: "数量",
      prop: "supplyName",
    }, {
      label: "金额",
      prop: "supplyName",
    },
    {
      label: "状态",
      prop: "netCashFlowGrowth",
      fixed: "right",
      width: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.isActive ? "success" : ""}>
          {
            row.isActive ? "已锁定" : "未锁定"
          }
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 100,
      slot: "operation"
    }
  ]
  const AddSelete = ref([]);
  const rules: any = {
    name: [
      { required: true, message: "请选择产品名称", trigger: 'blur' }
    ],
    num: [
      {
        required: true,
        validator: (rule: any, value: number, callback: () => void) => {
          if (!value || value > 10000000 || !Number.isInteger(Number(value))) {
            return callback(new Error('请输入到货数量，整数数值'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ],
  };
  const StubimAddFrom = reactive({
    name: "",
    num: ""
  });

  function CloseEntryPlatform(row: FormInstance | undefined) {
    ShowEchartsData()
    AddVisible.value = false;
  }

  function SubtimEntryPlatform(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const data = qs.stringify({
        productName: StubimAddFrom.name,
        productQuantity: Number(StubimAddFrom.num),
        taskId: route.query.taskId,
        planId: route.query.planId,
        sEId: sessionStorage.getItem("seiId"),
      });
      const res = await ProductInStockCreate(data);
      if (res.success) {
        CloseEntryPlatform(row);
      } else {
        ElMessage.error(res.msg)
      }
    })
  }


  async function ShowEchartsData() {
    const data = qs.stringify({
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    const res = await GetProductInStockCategoryNums(data);
    if (!res.success) {
      ElMessage.error(res.msg)
      return
    } else {
      nextTick(() => {
        const chartDom = document.getElementById('inventory');
        const myChart = echarts.init(chartDom);
        const datas = [
          {
            "productName": "键盘",
            "nums": 0
          },
          {
            "productName": "打印机",
            "nums": 0
          },
          {
            "productName": "鼠标",
            "nums": 0
          },
          {
            "productName": "智能手机",
            "nums": 0
          },
          {
            "productName": "笔记本电脑",
            "nums": 0
          },
          {
            "productName": "显示器",
            "nums": 0
          },
        ]
        res.data.forEach(item => {
          const foundItem = datas.find(a => item.productName == a.productName)
          if (foundItem) {
            foundItem.nums = item.nums
          }
        })
        const option = {
          tooltip: {
            trigger: 'axis',
            formatter: (item) => {
              return `
            <p>${item[0].value.productName}</p>
            <p>数量：${item[0].value.nums}</p>
          `
            }
            // axisPointer: {
            //   type: 'shadow'
            // }
          },
          dataset: {
            dimensions: ['productName', 'nums'],
            source: datas
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: { type: 'category' },
          yAxis: { minInterval: 1 },
          series: [{ type: 'bar', }]
        };
        option && myChart.setOption(option);
        window.onresize = function () {
          myChart.resize();
        }
      }
      )
    }
  }
  onMounted(() => {
    nextTick(() => {
      ShowEchartsData()
    })
  })
  return {
    rules,
    columns,
    loading,
    dataList,
    columns2,
    loading2,
    dataList2,
    AddSelete,
    AddVisible,
    DialogVisible,
    StubimAddFrom,
    RefStubimAddFrom,
    CloseEntryPlatform,
    SubtimEntryPlatform,
  }
}
